package com.album.utils.down;

import java.util.List;

import com.album.R;
import com.album.utils.MyLog;
import com.album.utils.down.AsyncImageLoader.ImageCallback;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;

public class ImageAndTextListAdapter extends ArrayAdapter<ImageAndText> {
	 
    private GridView gridView;
    private AsyncImageLoader asyncImageLoader;
    private Context context;
  
    
    public ImageAndTextListAdapter(Context context, List<ImageAndText> imageAndTexts, GridView gridView) {
        super(context, 0, imageAndTexts);
        this.gridView = gridView;
        this.context = context;
        asyncImageLoader = new AsyncImageLoader();
    }
 
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Inflate the views from XML
        View rowView = convertView;
        final ViewCache viewCache;
        if (rowView == null) {
            LayoutInflater inflater = LayoutInflater.from(context);
            viewCache = new ViewCache();
            rowView = inflater.inflate(R.layout.expandablegrid_item, null);
            viewCache.imageView = (ImageView)rowView.findViewById(R.id.itemImage);
            rowView.setTag(viewCache);
        } else {
            viewCache = (ViewCache) rowView.getTag();
        }
        ImageAndText imageAndText = getItem(position);
 
        // Load the image and set it on the ImageView
        String imageUrl = imageAndText.getImageUrl(); 
        viewCache.imageView.setTag(imageUrl);
        Drawable cachedImage = asyncImageLoader.loadDrawable(imageUrl, new ImageCallback() {
            public void imageLoaded(Drawable imageDrawable, String imageUrl) {

                MyLog.debug(getClass(), "===========imageDrawable =======:"+imageDrawable.getIntrinsicHeight());
                ImageView imageViewByTag = (ImageView) viewCache.imageView.findViewWithTag(imageUrl);
                if (imageViewByTag != null) {
//                    MyLog.debug(getClass(), "===========cachedImage ok=======");
                    imageViewByTag.setImageDrawable(imageDrawable);
                } 
            }
        });
//        MyLog.debug(getClass(), "===========cachedImage =======:"+cachedImage.getIntrinsicHeight());
        viewCache.imageView.setImageDrawable(cachedImage); 
 
        return rowView;
    }
    
}